<?php


namespace App\Model;


use App\Tool\Json;
use App\Tool\Obj;
use Exception;
use Illuminate\Support\Facades\Redis;

/**
 * App\Model\Order
 *
 * @property int $id
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property string $order_no 订单编号
 * @property string $user_id 用户
 * @property int $seller_id 商铺
 * @property int $pay_time 支付时间
 * @property int $delivery_type 配送方式,1是快递，2是自提
 * @property string $note 备注
 * @property float $total_money 订单总金额,不包含如何优惠
 * @property float $real_money 订单总金额(优惠后金额)
 * @property float|null $pay_money 实际支付金额
 * @property float $freight 运费
 * @property int $status 1待付款，11已支付，22已取消
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereDeliveryType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereFreight($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereNote($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereOrderNo($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order wherePayMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order wherePayTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereRealMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereSellerId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereTotalMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereUserId($value)
 * @mixin \Eloquent
 * @property int $order_transaction_id 订单交易id,订单交易表金额不一定等于当前订单金额,因为交易表可能对应多张订单
 * @property int $address_id 订单地址
 * @property-read \App\Model\Address $address
 * @property-read mixed $delivery_type_dec
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\OrderGoods[] $order_goods
 * @property-read int|null $order_goods_count
 * @property-read \App\Model\OrderTransaction $order_transaction
 * @property-read \App\Model\User $user
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereAddressId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereOrderTransactionId($value)
 * @property int $address_copy_id 副本地址id,副本地址是订单生成时的地址，不会随着地址修改而变动
 * @property-read \App\Model\AddressCopy $address_copy
 * @property-read \App\Model\StoreCopy|null $store_copy
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\Order whereAddressCopyId($value)
 */
class Order extends Base
{

    protected $table = 'order';


    protected $fillable = ['order_no', 'user_id', 'seller_id', 'pay_time', 'delivery_type', 'note', 'total_money', 'real_money', 'pay_money', 'freight', 'status','order_transaction_id','address_id','address_copy_id','expired_time'];

    protected $appends=['delivery_type_dec','expired_time_with_seconds'];


    function user(){


        return $this->belongsTo(User::class,'user_id','id');
    }

    function order_goods(){

        return $this->hasMany(OrderGoods::class,'order_id','id');
    }

    /**
     * 配送类型字符串
     * Create by PeterYang
     * 2020/06/20 18:16:32
     * Email:904801074@qq.com
     * @return mixed|string
     */
    function getDeliveryTypeDecAttribute()
    {

        $delivery_type=$this->attributes['delivery_type']??'';

        if(!$delivery_type) return $delivery_type;

        switch ($delivery_type){

            case '1':

                return '快递';

                break;

            case '2':

                return '自提';

                break;


        }


        return $delivery_type;

    }

    function getPayTimeAttribute($value)
    {
        if(!$value) return '';

        return date('Y-m-d H:i:s',$value);

    }

    function order_transaction(){


        return $this->belongsTo(OrderTransaction::class,'order_transaction_id','id');
    }


    function address(){

        return $this->belongsTo(Address::class,'address_id','id');
    }


    function address_copy(){

        return $this->belongsTo(AddressCopy::class,'address_copy_id','id');
    }

    /**
     * 库存回滚
     * Create by Peter
     * 2020/06/12 09:48:28
     * Email:904801074@qq.com
     * @param $id
     */
    function rollbackStock($id){


        $order=Order::with('order_goods.snapped_sku.snapped')
            ->with('order_goods.snapped_sku.goods_sku')
            ->has('order_goods')->findOrFail($id);


        foreach ($order->order_goods as $value){

            $snapped_sku_id=$value['snapped_sku_id'];

            $num=$value['num'];

            $goods_sku_id=$value['goods_sku_id'];

            if($snapped_sku_id){

                //还在活动时间
                if(Obj::getAttr($value,'snapped_sku.snapped.is_time')){


                    Redis::incrby('snapped:num_goods_sku_id_' . $value['goods_sku_id'],$value['num']);

                }

            }else{

                GoodsSku::findOrFail($goods_sku_id)->increment('num',$num);

            }


        }

//        exit();


    }

    function store_copy(){

        return $this->hasOne(StoreCopy::class,'order_id','id');
    }


    /**
     * 订单取消
     * Create by Peter
     * 2020/06/19 09:23:40
     * Email:904801074@qq.com
     * @param $user_id
     * @param $order_id
     * @throws Exception
     */
    function order_cancel($user_id,$order_id){

        try {

            \DB::beginTransaction();

            Redis::multi();

            $order_info=Order::where('user_id', $user_id)
                ->where('status',1)
                ->where('id', $order_id)->first();

            if(!$order_info) throw new \Exception('该订单不可取消');

            $order_info->fill(['status' => 22])->save();


            $this->rollbackStock($order_id);

            \DB::commit();

            Redis::exec();


//            return Json::code(1, 'success');

        } catch (Exception $exception) {

            \Log::debug($exception->getMessage());

            Redis::discard();

            \DB::rollBack();

            throw new Exception($exception->getMessage());

//            return Json::code(2, '网络错误，请重试');

        }
    }

    /**
     * 订单过期剩余时间（单位秒）
     * Create by PeterYang
     * 2020/06/20 18:22:57
     * Email:904801074@qq.com
     * @return false|int
     */
    function getExpiredTimeWithSecondsAttribute()
    {


        $expired_time=$this->attributes['expired_time'];

        $expired_time=strtotime($expired_time);

        if($expired_time<0) return false;

        $expired_time=$expired_time-time();

        if($expired_time<0) return false;

        return $expired_time;


    }


    function receipt_code(){

        return $this->hasOne(ReceiptCode::class,'order_id','id');
    }


    function order_mention(){

        return $this->hasOne(OrderMention::class,'order_id','id');
    }

}
